package com.weishui.downloading.download;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.weishui.downloading.app.DownLaodWindow;


public class MergeFilesThread implements Runnable{

	private String downLoadFileName;
	private int downLoadThreadCount;
	public MergeFilesThread(String downLoadFileName,int downLoadThreadCount){
		this.downLoadFileName = downLoadFileName;
		this.downLoadThreadCount = downLoadThreadCount;
	}
	
	private InputStream inputStream;
	private OutputStream outputStream;
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(DwnLoadOperator.DOWNLAOD_COUNT != 0){
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			outputStream = new FileOutputStream(new File(downLoadFileName));
			int readSize;
			byte[] readData = new byte[1024*20];
			for (int i=0;i<downLoadThreadCount;i++) {
				File partFile = new File(downLoadFileName + ".part" + i);
				inputStream = new FileInputStream(partFile);
				while((readSize = inputStream.read(readData)) != -1){
					outputStream.write(readData, 0, readSize);
				}
				inputStream.close();
				partFile.delete();
			}
			outputStream.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		DownLaodWindow.addLog("下载成功!");
	}

}
